﻿@using SmartStore.AmazonPay.Services;
@model SmartStore.AmazonPay.Models.AmazonPayViewModel

<script>
	$(function () {

		window.onAmazonLoginReady = function() {
			try {
				amazon.Login.setClientId('@Html.Raw(Model.ClientId)');
			}
			catch (e) {
				console.log(e);
				displayNotification(e, 'error');
			}
		};

		window.onAmazonPaymentsReady = function () {
			initButtons();
		};

		function initButtons() {
			var isAuthentication = @((Model.Type == AmazonPayRequestType.AuthenticationPublicInfo).ToString().ToLower());
			var scope = 'profile';

			try {
				if (!isAuthentication) {
					scope += ' payments:widget payments:shipping_address payments:billing_address';

					@if (Model.Logout)
					{
						<text>amazon.Login.logout();</text>
					}
				}
			}
			catch (e) {
				console.log(e);
				displayNotification(e, 'error');
			}

			try {
				OffAmazonPayments.Button(isAuthentication ? 'amazon-pay-auth-button' : 'amazon-pay-login-button', '@Html.Raw(Model.SellerId)', {
					type: '@(Model.ButtonType ?? (Model.Type == AmazonPayRequestType.AuthenticationPublicInfo ? "LwA" : "PwA"))',
					color: '@(Model.ButtonColor ?? "Gold")',
					size:  '@(Model.ButtonSize ?? "small")',
					language: '@(Model.LanguageCode ?? "de-DE")',
					authorization: function () {
						if (isAuthentication) {
							amazon.Login.authorize({ scope: scope }, '@Html.Raw(Model.ButtonHandlerUrl)');
						}
						else {
							$.ajax({
								type: 'POST',
								url: '@Url.Action("SaveCartData", "ShoppingCart", new { area = "" })',
								data: $('#startcheckout').closest('form').serialize(),
								success: function (response) {
									if (response.success) {
										amazon.Login.authorize({ scope: scope }, '@Html.Raw(Model.ButtonHandlerUrl)');
									}
									else {
										displayNotification(response.message, 'error');
									}
								}
							});
						}
					},
					onError: function (e) {
						displayNotification(e.getErrorCode() + ': ' + e.getErrorMessage(), 'error');
					}
				});
			}
			catch (e) {
				console.log(e);
				displayNotification(e, 'error');
			}
		}

		if (!(window.amazon != null && window.amazon.Login != null)) {
			var elem = document.createElement('script'),
				s = document.getElementsByTagName('script')[0];

			elem.type = 'text/javascript';
			elem.async = true;
			elem.src = '@Html.Raw(Model.WidgetUrl)';
			s.parentNode.insertBefore(elem, s);
		}
		else {
			initButtons();
		}
    });
</script>
